#!/usr/local/bin/ruby
# Copyright (C) 2003-2010 Wang Pengcheng <wpc0000@gmail.com>
# , released under the MIT license
# You may obtain a template of the MIT License at
# http://www.opensource.org/licenses/mit-license.php
$KCODE = 'utf8'

require 'erb'

file = ARGV[0]
result_filename = File.basename(file, '.txt')+'.tex'
UNIT_BASE = -7
LINE_ITEM_SIZE = 4

delays= []
discard_delays =[]
losts = []

File.read(file).split(/\n|\r/).each do |line|
  if line=~/.+\{(\d+),(\d+\.?\d+)\}/
    data = Regexp.last_match
    size = data[1].to_i
    delay = data[2].to_f

    if size==5000
      delays << delay
    elsif size!=0
      discard_delays << delay
    end
  end

  if line=~/\((\d+)\)(\d+\.+\d+)/
    data = Regexp.last_match
    losts << data[2].to_f if data[1].to_i!=0
  end
end

def mean(data)
  tot = 0
  data.each {|i|tot+=i}
  tot/data.length
end

def std(data)
  m = mean(data)
  tot = 0
  data.each do |i|
    tot += (i-m)**2
  end
  tot /= (data.length-1)
  tot**0.5
end

NS = [[1.645, 90], [1.96, 95], [2.576, 99]]
def ci(m,st,n, constN = 39)
  constN+=1
  barmu = n*st/constN**0.5
  "#{n}&#{m-barmu}&#{m+barmu}\\\\"
end

def ciFormat(m,st,n, constN = 39)
  constN+=1
  barmu = n*st/constN**0.5
  "#{n}&$#{m}\\pm{}#{barmu}$&$\\pm{}#{100*barmu/m}\\%$\\\\"
end

def delayBatchesPut(delays, discard_delays)
  res = ''
  all = delays + discard_delays
  num = 0
  all.each do |i|
    num += 1
    spl = '&'
    newline = false
    if num%LINE_ITEM_SIZE == 0
      spl = "\\\\"
      newline = true
    end
    if num<=delays.size
      res += "#{i}#{spl}"
    else
      res += "\\emph{\\textcolor{red}{#{i}}}#{spl}"
    end
    if newline
      res += "\n"
    end
  end
  res
end

def cisPut(m,st, ns)
  res = ''
  ns.each do |n|
    res += "#{n[1]}\\%&"+ci(m,st,n[0])+"\n"
  end
  res
end

def cisFormatPut(m,st, ns)
  res = ''
  ns.each do |n|
    res += "#{n[1]}\\%&"+ciFormat(m,st,n[0])+"\n"
  end
  res
end

def lostsPut(losts)
  num = 0
  res= ''
  losts.each do |i|
    num += 1
    if num%LINE_ITEM_SIZE == 0
      res+="#{i}\\\\\n"
    else
      res+="#{i}&"
    end
  end
  res
end

template = ERB.new(File.read('template.tex'))
File.open(result_filename,'w')do |nf|
  nf.puts template.result(binding)
end

